package com.future.mayi.qsale.activity;

import android.graphics.Color;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.TextView;

import com.blankj.utilcode.util.SpanUtils;
import com.future.baselib.entity.DefaultResponse;
import com.future.baselib.utils.ApiCst;
import com.future.baselib.utils.HttpRequest;
import com.future.mayi.R;
import com.future.mayi.activity.BaseTitleActivity;
import com.future.mayi.app.App;
import com.future.mayi.qsale.adapter.SignatureAdapter;
import com.future.mayi.qsale.model.RedPacketInfoModel;
import com.future.mayi.qsale.response.PrizeDrawResponse;
import com.future.mayi.qsale.response.RedPacketInfoResponse;
import com.future.mayi.qsale.view.LotteryView;
import com.future.mayi.qsale.view.SwitchButton;
import com.future.mayi.utils.KefuUtils;
import com.future.mayi.utils.Navigator;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * Created by Administrator on 2018/6/20.
 */

public class RedPacketActivity extends BaseTitleActivity implements LotteryView.PrizeListener {

    @BindView(R.id.tv_sign_in_days)
    TextView tvSignInDays;
    @BindView(R.id.recycler_view)
    RecyclerView recyclerView;
    @BindView(R.id.tv_lottery_num)
    TextView tvLotteryNum;
    @BindView(R.id.tv_unit)
    TextView tvUnit;
    @BindView(R.id.tv_decade)
    TextView tvDecade;
    @BindView(R.id.tv_hundreds)
    TextView tvHundreds;
    @BindView(R.id.tv_thousands)
    TextView tvThousands;
    @BindView(R.id.btn_qiandao)
    TextView btn_qiandao;
    @BindView(R.id.lotteryview)
    LotteryView lotteryView;
    @BindView(R.id.sb_remind)
    SwitchButton sbRemind;
    @BindView(R.id.tv_lottery_rule)
    TextView tvLotteryRule;

    private SignatureAdapter mSignatureAdapter;


    private int mContinuity;
    private int mPrizeCardNum;

    @Override
    protected void initLayout() {
        setContentView(R.layout.activity_red_packet);
    }

    @Override
    protected void initView() {

    }

    @Override
    protected void initDates() {
        getRedPackInfo();
    }

    @Override
    protected void initListener() {

    }

    @Override
    protected void initTopBar() {
        initBack();
        getTitleText().setText("领红包");
        getRightImg().setImageResource(R.drawable.bottom_kefu);
        getRightImg().setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                KefuUtils.startActivity(RedPacketActivity.this);
            }
        });
    }

    @OnClick({R.id.tv_diejia, R.id.btn_qiandao, R.id.tv_red_packet_more, R.id.tv_lottery_rule})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.tv_diejia:

                break;
            case R.id.btn_qiandao:
                redPackSignIn();
                break;
            case R.id.tv_red_packet_more:
                Navigator.navigatorMyRedPacketActivity(this);
                break;
            case R.id.tv_lottery_rule:
                Navigator.navigarorRedPacketRuleActivity(this);
                break;
        }
    }

    private void redPackSignIn() {
        showLoadingDialog();
        new HttpRequest<DefaultResponse>()
                .with(this)
                .setApiCode(ApiCst.redpackSignIn)
                .addParam("token", App.getToken(this))
                .setListener(new HttpRequest.OnNetworkListener<DefaultResponse>() {
                    @Override
                    public void onSuccess(DefaultResponse response) {
                        dissmissLoadingDialog();
                        toast(response.message);

                        try {
                            JSONObject object = new JSONObject(response.content);
                            mContinuity = object.optInt("continuity");
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }

                        setIsSigned(true);
                        setSignContinuity(mContinuity);
                        refreshRedPackList();
                    }

                    @Override
                    public void onFail(String message, DefaultResponse response) {
                        dissmissLoadingDialog();
                        toast(message);
                    }
                }).start(new DefaultResponse());

    }

    private void getRedPackInfo() {
        showLoadingDialog();
        new HttpRequest<RedPacketInfoResponse>()
                .with(this)
                .setApiCode(ApiCst.redpackGetInfo)
                .addParam("token", App.getToken(this))
                .setListener(new HttpRequest.OnNetworkListener<RedPacketInfoResponse>() {
                    @Override
                    public void onSuccess(RedPacketInfoResponse response) {
                        dissmissLoadingDialog();
                        setRedPackList(response.getRedpackList());
                        setSignContinuity(response.getRedPacketInfoModel().getContinuity());
                        setPrizeCardNum(response.getRedPacketInfoModel().getPrize_card_num());
                        setIsSigned(response.getRedPacketInfoModel().isSignIn());
                        lotteryView.setPrizeInfo(response.getPrizeList());
                        lotteryView.setPrizeListener(RedPacketActivity.this);
                        setRedPackTotal();
                    }

                    @Override
                    public void onFail(String message, RedPacketInfoResponse response) {
                        dissmissLoadingDialog();
                        toast(message);
                        RedPacketActivity.this.finish();
                    }
                }).start(new RedPacketInfoResponse());
    }

    private void setRedPackList(List<RedPacketInfoModel.RedpackListBean> redpackListBeans) {
        LinearLayoutManager ms = new LinearLayoutManager(this);
        ms.setOrientation(LinearLayoutManager.HORIZONTAL);// 设置 recyclerview 布

        recyclerView.setLayoutManager(ms);
        recyclerView.setNestedScrollingEnabled(false);
        recyclerView.setHasFixedSize(false);
        recyclerView.setNestedScrollingEnabled(false);

        mSignatureAdapter = new SignatureAdapter(this, redpackListBeans);
        recyclerView.setAdapter(mSignatureAdapter);
    }

    //签到成功后调用
    private void refreshRedPackList() {
        for (int i = 0; i < mSignatureAdapter.getList().size(); i++) {
            if (mSignatureAdapter.getList().get(i).getDay() <= mContinuity) {
                mSignatureAdapter.getList().get(i).setHasSignature(true);
            } else {
                mSignatureAdapter.getList().get(i).setHasSignature(false);
            }
        }
        mSignatureAdapter.notifyDataSetChanged();
        setRedPackTotal();
    }

    private void setSignContinuity(int continuity) {
        this.mContinuity = continuity;
        tvSignInDays.setText(new SpanUtils()
                .append("连续签到 ")
                .append(String.valueOf(mContinuity)).setForegroundColor(Color.parseColor("#F41B45")).setFontProportion(2)
                .append(" 天").create());
    }

    private void setPrizeCardNum(int prizeCardNum) {
        this.mPrizeCardNum = prizeCardNum;
        tvLotteryNum.setText(new SpanUtils()
                .append("抽奖卡 x ")
                .append(String.valueOf(mPrizeCardNum)).setForegroundColor(Color.parseColor("#D7AC6D")).setFontProportion(1.6f)
                .create());
    }

    private void setIsSigned(boolean isSigned) {
        if (isSigned) {
            btn_qiandao.setBackgroundResource(R.drawable.hongbao_bukeqiandao);
            btn_qiandao.setEnabled(false);
        } else {
            btn_qiandao.setBackgroundResource(R.drawable.hongbao_qiandao);
            btn_qiandao.setEnabled(true);
        }
    }

    private void setRedPackTotal() {

        List<RedPacketInfoModel.RedpackListBean> redpackListBeans = mSignatureAdapter.getList();
        if (redpackListBeans.size() > 0) {
            float totalNum = 0;
            for (int i = 0; i < redpackListBeans.size(); i++) {
                if (redpackListBeans.get(i).isHasSignature()) {
                    totalNum += redpackListBeans.get(i).getPar_value();
                }
            }
            int total = (int) totalNum;

            int g = total % 10;
            int sw = total / 10 % 10;
            int b = total / 100 % 10;
            int q = total / 1000 % 10;

            tvThousands.setText(String.valueOf(q));
            tvHundreds.setText(String.valueOf(b));
            tvDecade.setText(String.valueOf(sw));
            tvUnit.setText(String.valueOf(g));
        } else {
            tvUnit.setText(0);
            tvDecade.setText(0);
            tvHundreds.setText(0);
            tvThousands.setText(0);
        }

    }


    @Override
    public void getPrizeDraw() {

        //only for test
//        RedPacketInfoModel.PrizeInfoBean prizeInfoBean = new RedPacketInfoModel.PrizeInfoBean();
//        prizeInfoBean.setPrize_id(8);
//        prizeInfoBean.setPrize_name("50元话费");
//        prizeInfoBean.setPrize_img("http://api.shewuwang.com/uploads/20180626/e6d3f0364b83624d6d9876e52c38d987.jpg");
//        lotteryView.startPrizeAnimation(prizeInfoBean);

        new HttpRequest<PrizeDrawResponse>()
                .with(this)
                .setApiCode(ApiCst.PrizeDraw)
                .addParam("token", App.getToken(this))
                .setListener(new HttpRequest.OnNetworkListener<PrizeDrawResponse>() {
                    @Override
                    public void onSuccess(PrizeDrawResponse response) {
                        getRedPackInfo();
                        lotteryView.startPrizeAnimation(response.getPrizeInfoBean());
                    }

                    @Override
                    public void onFail(String message, PrizeDrawResponse response) {
                        toast(message);
                    }
                }).start(new PrizeDrawResponse());

    }
}
